package com.yc;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

public class URLDemo {

    // 父异常 IOException   子异常 MalformedURLException
    public static void main1(String[] args) throws IOException {
        String addr = "http://www.hyycinfo.com:80/index.html?a=1&b=2#abc";
        URL url = new URL(addr);
        // 输出 url 相关信息
        System.out.println("url.getProtocol() = " + url.getProtocol());
        System.out.println("url.getHost() = " + url.getHost());
        System.out.println("url.getPort() = " + url.getPort());
        System.out.println("url.getPath() = " + url.getPath());
        System.out.println("url.getQuery() = " + url.getQuery());
        // 获取连接
        URLConnection urlConnection = url.openConnection();
        InputStream in = urlConnection.getInputStream();

        // 字节流转字符流
        InputStreamReader isr = new InputStreamReader(in, "utf-8");

        // 字节流读取
//        byte[] bytes = new byte[128];
//        int count;
//        while (  (count = in.read(bytes))  > -1 ){
//            String s = new String(bytes,0,count);
//            System.out.println(s);
//        }

        String path = url.getPath();
        String filename;
        if (path == null || path.isEmpty()) {
            filename = "index.html";
        } else {
            int i = path.lastIndexOf("/");
            filename = path.substring(i + 1);
        }
        FileWriter fw = new FileWriter("d:/" + filename);

        // 字符流
        char[] chars = new char[128];
        int count;
        while ((count = isr.read(chars)) > 0) {
            String s = new String(chars, 0, count);
            System.out.print(s);
            fw.write(s);
        }

        fw.close();
        in.close();

    }

    /**
     * 下载文件到指定文件夹
     *
     * @param url
     * @param dir
     */
    public static void download(String url, String dir) throws IOException {
        URL u = new URL(url);
        URLConnection urlConnection = u.openConnection();

        // 自动创建目录
        File file = new File(dir);
        if (file.exists() == false) {
            file.mkdirs();
        }

        // 获取文件大小
        int contentLength = urlConnection.getContentLength();
        // 构建文件路径
        String filepath = dir + "/";
        int i = u.getPath().lastIndexOf("/");
        String filename = u.getPath().substring(i + 1);
        filepath += filename;

        System.out.printf("开始下载 %s 文件到 %s\n", url, filepath);
        try (InputStream in = urlConnection.getInputStream();
             FileOutputStream fos = new FileOutputStream(filepath)) {
            byte[] bytes = new byte[1024 * 100];
            int count;
            int downs = 0;   // 当前下载的总的字节数
            int rate = 0;    // 当前下载进度
            while ((count = in.read(bytes)) > -1) {
                downs += count;
                // 计算下载进度
                int r = downs * 100 / contentLength;
                // 下载进度发生变化, 则显示并更新进度,
                if (r > rate) {
                    rate = r;
                    System.out.println(rate + "%");
                }
                fos.write(bytes, 0, count);
            }
        }catch (IOException e){
            System.out.println(url + " 下载失败: " + e.getMessage());
        }
        System.out.printf("下载完成！\n");
    }

    public static void main(String[] args) throws IOException {
        String url = "http://softcdn12.mydown.com/cs/206nsoft/%E9%92%89%E9%92%89_bUzuMzed.exe";
        String dir = "d:/a";
        download(url, dir);
    }

}
